﻿#include "pokemonbattle.h"
#include <QMessageBox>
#include <QTimer>
#include <QFont>
#include <qrandom.h>

// Pokemon 基类实现
Pokemon::Pokemon(QObject* parent) : QObject(parent)
{
}

void Pokemon::takeDamage(int damage)
{
    currentHP -= damage;
    if (currentHP < 0) currentHP = 0;
}

int Pokemon::useSkill(int skillIndex)
{
    if (skillIndex < 0 || skillIndex >= skills.size()) return 0;

    // 基础伤害计算
    int baseDamage = attack;

    // 这里可以添加属性相克、技能威力等复杂计算
    switch (skillIndex) {
    case 0: baseDamage += 10; break; // 小技能
    case 1: baseDamage += 20; break; // 中等技能  
    case 2: baseDamage += 30; break; // 大技能
    case 3: baseDamage += 15; break; // 特殊技能
    }

    return baseDamage;
}

// Charmander 实现
Charmander::Charmander(QObject* parent) : Pokemon(parent)
{
    name = "小火龙";
    type = "火";
    level = 5;
    maxHP = 39;
    currentHP = maxHP;
    attack = 12;
    defense = 43;
    speed = 65;

    skills = { "火花", "火焰喷射", "龙之怒", "抓" };
}

int Charmander::useSkill(int skillIndex)
{
    int baseDamage = Pokemon::useSkill(skillIndex);

    // 火系技能加成
    if (skillIndex == 0 || skillIndex == 1) {
        baseDamage = static_cast<int>(baseDamage * 1.2);
    }

    return baseDamage;
}

// Bulbasaur 实现
Bulbasaur::Bulbasaur(QObject* parent) : Pokemon(parent)
{
    name = "妙蛙种子";
    type = "草/毒";
    level = 5;
    maxHP = 45;
    currentHP = maxHP;
    attack = 12;
    defense = 49;
    speed = 45;

    skills = { "藤鞭", "飞叶快刀", "阳光烈焰", "毒粉" };
}

int Bulbasaur::useSkill(int skillIndex)
{
    int baseDamage = Pokemon::useSkill(skillIndex);

    // 草系技能加成
    if (skillIndex == 0 || skillIndex == 1) {
        baseDamage = static_cast<int>(baseDamage * 1.2);
    }

    return baseDamage;
}

// PokemonBattle 实现
PokemonBattle::PokemonBattle(QWidget* parent)
    : QWidget(parent), playerPokemon(nullptr), opponentPokemon(nullptr), playerTurn(true)
{
    // 创建HP条
    //初始化精灵map
    initSpriteMap();
    playerHPBar = new QProgressBar(this);
    opponentHPBar = new QProgressBar(this);
    playerHPBar->setTextVisible(true);
    opponentHPBar->setTextVisible(true);
    playerHPBar->setRange(0, 100);
    opponentHPBar->setRange(0, 100);
    playerHPBar->setStyleSheet("QProgressBar::chunk { background-color: #4CAF50; }");
    opponentHPBar->setStyleSheet("QProgressBar::chunk { background-color: #4CAF50; }");

    // 创建名字和等级标签
    playerNameLabel = new QLabel(this);
    opponentNameLabel = new QLabel(this);
    playerLevelLabel = new QLabel(this);
    opponentLevelLabel = new QLabel(this);

    QFont nameFont("Microsoft YaHei", 10, QFont::Bold);
    playerNameLabel->setFont(nameFont);
    opponentNameLabel->setFont(nameFont);

    // 创建战斗信息标签
    battleMessageLabel = new QLabel("选择技能开始对战!", this);
    battleMessageLabel->setAlignment(Qt::AlignCenter);
    QFont messageFont("Microsoft YaHei", 9);
    //白色字体
    QPalette palette;
    palette.setColor(QPalette::WindowText, Qt::white);
    battleMessageLabel->setPalette(palette);


    // 创建技能按钮
    for (int i = 0; i < 4; ++i) {
        skillButtons[i] = new QPushButton(this);
        connect(skillButtons[i], &QPushButton::clicked, this, [this, i]() {
            if (playerTurn) {
                switch (i) {
                case 0: onSkill1Clicked(); break;
                case 1: onSkill2Clicked(); break;
                case 2: onSkill3Clicked(); break;
                case 3: onSkill4Clicked(); break;
                }
            }
            });
    }

    // 创建精灵显示区域（占位符）
    playerSpriteLabel = new QLabel("🐲", this);
    opponentSpriteLabel = new QLabel("🌱", this);
    playerSpriteLabel->setAlignment(Qt::AlignCenter);
    opponentSpriteLabel->setAlignment(Qt::AlignCenter);
    QFont spriteFont("Microsoft YaHei", 24);
    playerSpriteLabel->setFont(spriteFont);
    opponentSpriteLabel->setFont(spriteFont);

    // 设置布局
    mainLayout = new QVBoxLayout(this);

    // 对手信息布局
    opponentInfoLayout = new QHBoxLayout();
    opponentInfoLayout->setContentsMargins(10, 0, 10, 0);
    opponentInfoLayout->addWidget(opponentNameLabel);
    opponentInfoLayout->addWidget(opponentLevelLabel);
    opponentInfoLayout->addWidget(opponentHPBar);
    opponentInfoLayout->addStretch();

    // 玩家信息布局  
    playerInfoLayout = new QHBoxLayout();
    //设置水平两边的间距
    playerInfoLayout->setContentsMargins(10, 0, 10, 0);
    playerInfoLayout->addWidget(playerNameLabel);
    playerInfoLayout->addWidget(playerLevelLabel);
    playerInfoLayout->addWidget(playerHPBar);
    playerInfoLayout->addStretch();
    // 对战区域布局
    battleLayout = new QHBoxLayout();
    QVBoxLayout* opponentLayout = new QVBoxLayout();
    opponentLayout->addWidget(opponentSpriteLabel);
    opponentLayout->addLayout(opponentInfoLayout);


    QVBoxLayout* playerLayout = new QVBoxLayout();
    playerLayout->addWidget(playerSpriteLabel);
    playerLayout->addLayout(playerInfoLayout);
    battleLayout->addStretch();
    battleLayout->addLayout(opponentLayout);
    battleLayout->addLayout(playerLayout);
    battleLayout->addStretch();
    // 技能按钮布局
    skillsLayout = new QGridLayout();
    skillsLayout->setContentsMargins(250, 0, 350, 0);
    //加上水平侧边的间距，间距尽可能大
    for (int i = 0; i < 4; ++i) {
        skillsLayout->addWidget(skillButtons[i], i / 2, i % 2);

    }

    // 主布局组装
    QLabel* titleLabel = new QLabel("Pokemon 战斗", this);
    titleLabel->setAlignment(Qt::AlignCenter);
    titleLabel->setFont(QFont("Microsoft YaHei", 16));
    //白色字体
    QPalette palette1;
    palette1.setColor(QPalette::WindowText, Qt::white);
    titleLabel->setPalette(palette);
    mainLayout->addWidget(titleLabel);
    //设置选择框
    QHBoxLayout* selectLayout = new QHBoxLayout();
    QLabel* a = new QLabel("选择宝可梦");
    a->setPalette(palette1);
    //设置白色字体
    selectLayout->addStretch();
    QLabel* b = new QLabel("vs.");
    b->setPalette(palette1);
    selectLayout->addWidget(a);

    //白色字体

    selectLayout->addWidget(m_palyerSprites);
    selectLayout->addWidget(b);
    selectLayout->addWidget(m_opponentSprites);
    startBatterButton = new QPushButton("开始战斗");
    startBatterButton->setPalette(palette1);
    selectLayout->addWidget(b);
    selectLayout->addWidget(startBatterButton);
    selectLayout->addStretch();


    mainLayout->addLayout(selectLayout);
    mainLayout->addWidget(battleMessageLabel);
    mainLayout->addLayout(playerLayout);
    mainLayout->addLayout(battleLayout);
    mainLayout->addWidget(battleMessageLabel);
    mainLayout->addLayout(skillsLayout);

    // 设置默认宝可梦
    setPokemons(new Charmander(this), new Bulbasaur(this));
    connect(startBatterButton, &QPushButton::clicked, [this]() {
        QString palyerSparite = m_palyerSprites->currentText()+"玩家";
        QString opponentSparite = m_opponentSprites->currentText()+"敌人";
        Pokemon* palyer = m_spriteMap.value(palyerSparite);
        Pokemon* opponent = m_spriteMap.value(opponentSparite);
        setPokemons(palyer, opponent);
        updateUI();
        });

    //每次切换更新ui
    connect(m_palyerSprites, &QComboBox::currentTextChanged, [this]() {
        updateUI();
    });
    connect(m_opponentSprites, &QComboBox::currentTextChanged, [this]() {
        updateUI();
    });
}

void PokemonBattle::initSpriteMap()
{
    m_palyerSprites = new QComboBox;
    m_opponentSprites = new QComboBox; 
    CharmanderpPlayer = new Charmander(this);
    BulbasaurpPlayer = new Bulbasaur(this);
    CharmanderOppent = new Charmander(this);
    BulbasaurpOppent = new Bulbasaur(this);
    m_spriteMap.insert("小火龙玩家", CharmanderpPlayer);
    m_spriteMap.insert("小火龙敌人", CharmanderpPlayer);
    m_spriteMap.insert("妙蛙种子敌人", BulbasaurpOppent);
    m_spriteMap.insert("妙蛙种子玩家", BulbasaurpOppent);

    // 获取精灵对象的指针并添加到列表中
    m_palyerSprites->addItem("小火龙");
    m_palyerSprites->addItem("妙蛙种子");

    m_opponentSprites->addItem("妙蛙种子");
    m_opponentSprites->addItem("小火龙");

}


PokemonBattle::~PokemonBattle()
{
}

void PokemonBattle::setPokemons(Pokemon* player, Pokemon* opponent)
{
    playerPokemon = player;
    opponentPokemon = opponent;
    updateUI();
}

void PokemonBattle::startBattle()
{
    playerTurn = true;
    showBattleMessage("对战开始! " + playerPokemon->getName() + " vs " + opponentPokemon->getName());
    updateUI();
}

void PokemonBattle::updateUI()
{
    // 更新玩家信息
    playerNameLabel->setText(playerPokemon->getName());
    playerLevelLabel->setText("Lv." + QString::number(playerPokemon->getLevel()));
    //字体蓝色
    QPalette palette;
    palette.setColor(QPalette::WindowText, Qt::blue);
    playerNameLabel->setPalette(palette);
    playerLevelLabel->setPalette(palette);
    playerHPBar->setRange(0, playerPokemon->getMaxHP());
    playerHPBar->setValue(playerPokemon->getHP());
    playerHPBar->setFormat(QString("%1/%2").arg(playerPokemon->getHP()).arg(playerPokemon->getMaxHP()));

    // 更新对手信息
    opponentNameLabel->setText(opponentPokemon->getName());
    //字体蓝色
    opponentNameLabel->setPalette(palette);
    opponentLevelLabel->setPalette(palette);
    opponentLevelLabel->setText("Lv." + QString::number(opponentPokemon->getLevel()));
    opponentHPBar->setRange(0, opponentPokemon->getMaxHP());
    opponentHPBar->setValue(opponentPokemon->getHP());
    opponentHPBar->setFormat(QString("%1/%2").arg(opponentPokemon->getHP()).arg(opponentPokemon->getMaxHP()));

    // 更新技能按钮
    QVector<QString> playerSkills = playerPokemon->getSkills();
    for (int i = 0; i < 4; ++i) {
        if (i < playerSkills.size()) {
            skillButtons[i]->setText(playerSkills[i]);
            skillButtons[i]->setEnabled(true);
        }
        else {
            skillButtons[i]->setText("");
            skillButtons[i]->setEnabled(false);
        }
    }
}

void PokemonBattle::onSkill1Clicked() { executeTurn(0); }
void PokemonBattle::onSkill2Clicked() { executeTurn(1); }
void PokemonBattle::onSkill3Clicked() { executeTurn(2); }
void PokemonBattle::onSkill4Clicked() { executeTurn(3); }

void PokemonBattle::executeTurn(int playerSkillIndex)
{
    if (!playerTurn || !playerPokemon || !opponentPokemon) return;

    playerTurn = false;

    // 玩家攻击
    int playerDamage = playerPokemon->useSkill(playerSkillIndex);
    opponentPokemon->takeDamage(playerDamage);

    QString skillName = playerPokemon->getSkills()[playerSkillIndex];
    showBattleMessage(playerPokemon->getName() + " 使用了 " + skillName + "! 造成了 " +
        QString::number(playerDamage) + " 点伤害!");

    updateUI();
    checkBattleEnd();
    if (opponentPokemon->isFainted()) return;

    // 对手攻击（简单AI，随机选择技能）
    QTimer::singleShot(1000, this, [this]() {
        if (!opponentPokemon || opponentPokemon->isFainted()) return;

        int opponentSkillIndex = QRandomGenerator::global()->bounded(opponentPokemon->getSkills().size());
        int opponentDamage = opponentPokemon->useSkill(opponentSkillIndex);
        playerPokemon->takeDamage(opponentDamage);

        QString opponentSkillName = opponentPokemon->getSkills()[opponentSkillIndex];
        showBattleMessage(opponentPokemon->getName() + " 使用了 " + opponentSkillName + "! 造成了 " +
            QString::number(opponentDamage) + " 点伤害!");

        updateUI();
        checkBattleEnd();

        playerTurn = true;
        });
}

void PokemonBattle::checkBattleEnd()
{
    if (playerPokemon->isFainted()) {
        showBattleMessage(playerPokemon->getName() + " 倒下了! " + opponentPokemon->getName() + " 获胜!");
        for (int i = 0; i < 4; ++i) {
            skillButtons[i]->setEnabled(false);
        }
    }
    else if (opponentPokemon->isFainted()) {
        showBattleMessage(opponentPokemon->getName() + " 倒下了! " + playerPokemon->getName() + " 获胜!");
        for (int i = 0; i < 4; ++i) {
            skillButtons[i]->setEnabled(false);
        }
    }
}

void PokemonBattle::showBattleMessage(const QString& message)
{
    battleMessageLabel->setText(message);
}